#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# File: gui.py
# Author: Finnur Smári Torfason
# Date: 23/11/2011  
# GUI fyrir aflalista
#
import wx, time, os.path, time, sys

from utils import helpers, gatherInfo, db
#, afla_main, afla_landings 
from utils import categorize as cat
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
from threading import Thread

from utils.event import ResultEvent

EVT_RESULT_ID = 104

kvList = helpers.getKvList()

#################### Þráða klasar ####################
class dbThread(Thread):
  def __init__(self, notify_window, kvtime, check, currKvtime):
    Thread.__init__(self)
    self._notify_window = notify_window
    self.kvtime = kvtime
    self.check = check
    self.currKvtime = currKvtime
    self.start()
  
  def run(self):
    t0 = time.time()
    
    gatherInfo.main(self.kvtime, self._notify_window, self.check, self.currKvtime)
    
    t1 = int(time.time() - t0)
    hrs = t1/3600
    mins = (t1%3600)/60
    secs = (t1%3600)%60
    totalTime = str(hrs) + ' klst. ' + str(mins) + ' mínútur, og ' + str(secs) + ' sekúndur!'
    
    wx.PostEvent(self._notify_window, ResultEvent('\nTíminn sem tók að uppfæra gagnagrunninn: ' + totalTime, 1))
######################################################

#################### GUI Klasinn #####################
class myGUI(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(400,340))
    
    # Menubar
    menu = wx.MenuBar()
		
    # Menu's
    file = wx.Menu()
    file.Append(101, '&Quit\tCtrl+Q', 'Loka forriti')
		
    menu.Append(file, '&File')
		
    # Tabs
    nb = wx.Notebook(self, wx.ID_ANY)
		
    # MyPage(parent, mycolor, mytext)
    self.page1 = updateDB(nb)
    self.page2 = createList(nb)
    self.page3 = landingSelection(nb)
    # AddPage(page, tab title)
    nb.AddPage(self.page1, 'Uppfæra')
    nb.AddPage(self.page2, 'Útbúa lista')
    nb.AddPage(self.page3, 'Einstakar landanir')
		
    # Frame objects
    self.SetIcon(wx.Icon('./imgs/aflaIcon.gif', wx.BITMAP_TYPE_GIF))
    self.CreateStatusBar()
    self.SetMenuBar(menu)
		
    # Bindings
    self.Bind(wx.EVT_MENU, self.onQuit, id = 101)
    self.Bind(wx.EVT_BUTTON, self.onUpdate, id = 201)
    self.Bind(wx.EVT_BUTTON, self.onCategorize, id = 301)
    self.Bind(wx.EVT_BUTTON, self.onShowLandings, id = 401)
    helpers.EVT_RESULT(self,self.postMessage)
		
    self.dirname = ''
    self.clear = 0
		
    # worker threads
    self.updateWorker = None
		
    self.Show(True)

  def onQuit(self, e):
    self.Close()
	
  
  def onUpdate(self, e):
    if not self.updateWorker:
      self.page1.msgBox.Clear()
    kvtime = self.page1.kvtime.GetValue() # Fetch the value of kvtime
		
    if self.updateWorker:
      if not self.updateWorker.isAlive():
        self.updateWorker = None

    if not kvtime:
      self.page1.msgBox.AppendText('Vantar kvótaár\n')
    elif not self.updateWorker:
      self.page1.msgBox.AppendText('Byrja uppfærslu á aflaupplýsingum\n')
      self.updateWorker = dbThread(self, kvtime, self.page1.cb.GetValue(), helpers.currKv())
	
  def onCategorize(self, e):
    if self.page2.date1.GetValue() == self.page2.date2.GetValue():
      dlg = wx.MessageDialog(self, 'Sömu dagsetningar valdar!', 'Villa!', wx.OK|wx.ICON_INFORMATION)
      dlg.ShowModal()
      dlg.Destroy()
    else:
      dlg = wx.FileDialog(self, 'Choose a file', self.dirname, '', '*.*', wx.SAVE | wx.OVERWRITE_PROMPT)
      if dlg.ShowModal() == wx.ID_OK:
        # Finnum filename
        self.dirname = dlg.GetDirectory()
        self.filename = dlg.GetFilename()
        filename = os.path.join(self.dirname, self.filename)
        cat.main(self.page2.date1.GetValue(), self.page2.date2.GetValue(), filename)
			
      dlg.Destroy()
	
  def onShowLandings(self, e):
    kvtime = self.page3.kvtime.GetValue()
    shipNo = self.page3.shipNo.GetValue()
		
    if self.clear:
      self.page3.list.DeleteAllItems()
      self.clear = 0
		
    if (not kvtime) or (not shipNo):
      dlg = wx.MessageDialog(self, 'Vantar annaðhvort kvótaár, eða '
                            + 'skipaskrárnúmer!', 'Villa!', wx.OK|wx.ICON_INFORMATION)
      dlg.ShowModal()
      dlg.Destroy()
    else:
      landingList = db.getLandingList(kvtime, shipNo)
			
      for i in landingList:
        index = self.page3.list.InsertStringItem(sys.maxint, str(helpers.formatDate(i[2])))
        self.page3.list.SetStringItem(index,1,str(float(i[5])/1000))
      self.clear = 1
	
  def postMessage(self, e):
    self.page1.msgBox.AppendText(str(e.data))
    #if e.release == 1:
    #	self.worker = None:
######################################################

########### Uppfæra gagnagrunn tab klasinn ###########
class updateDB(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self,parent,wx.ID_ANY)
    self.SetBackgroundColour("Grey")
		
    # Kvótaár selection box
    wx.StaticText(self, -1, 'Kvótaár:', pos=(10,10))
    self.kvtime = wx.ComboBox(self, -1, pos=(100,10), size=(100,30), choices=kvList)
		
    # Uppfæra báta
    self.cb = wx.CheckBox(self, -1, 'Uppfæra skipaskrárnúmer', (10, 50))
    self.cb.SetValue(True)
		
    # Uppfæra button
    self.updateBtn = wx.Button(self, 201, label='Uppfæra', pos = (300,50), size=(80,30))

    # Message box
    self.msgBox = wx.TextCtrl(self, -1, pos=(10,90), size=(370,140), style=wx.TE_MULTILINE|wx.TE_READONLY)
######################################################

############## Útbúa lista tab klasinn ###############
class createList(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self,parent,wx.ID_ANY)
    self.SetBackgroundColour("Grey")
		
    # Date controls
    wx.StaticText(self, -1, 'Dagsetning 1:', pos=(10,10))
    self.date1 = wx.DatePickerCtrl(self, -1, pos=(155,10), size=(150,-1))
    wx.StaticText(self, -1, 'Dagsetning 2:', pos=(10,45))
    self.date2 = wx.DatePickerCtrl(self, -1, pos=(155,45), size=(150,-1))

    # Útbúa lista button
    self.catBtn = wx.Button(self, 301, label='Útbúa lista', pos = (105,80), size=(90,30))
######################################################

########### Einstakar landanir tab klasinn ###########
class landingSelection(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self,parent,wx.ID_ANY)
    self.SetBackgroundColour("Grey")
		
    hbox = wx.BoxSizer(wx.HORIZONTAL)
    panel = wx.Panel(self, -1, pos=(10,120), size=(370, 120))
		
    # Kvótaár selection box
    wx.StaticText(self, -1, 'Kvótaár:', pos=(10,10))
    self.kvtime = wx.ComboBox(self, -1, pos=(155,10), size=(100,30), choices=kvList)
		
    # Skipaskrárnr. box
    wx.StaticText(self, -1, 'Skipaskrárnúmer:', pos=(10,45))
    self.shipNo = wx.TextCtrl(self, -1, pos=(155,45), size=(70,30))
		
    # Sækja landanir button
    self.updateBtn = wx.Button(self, 401, label='Sækja landanir', pos = (105,80), size=(110,30))
    
    self.list = AutoWidthListCtrl(panel)
    self.list.InsertColumn(0, 'Dags.', width=140)
    self.list.InsertColumn(1, 'Afli', width=140)
    
    hbox.Add(self.list, 1, wx.EXPAND)
    panel.SetSizer(hbox)
######################################################

############### Klasi fyrir ListCtrl #################
class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
  def __init__(self, parent):
    wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
    ListCtrlAutoWidthMixin.__init__(self)
######################################################

def main():
  app = wx.App()
  myGUI(None, -1, 'Aflalisti')
  app.MainLoop()

if __name__ == '__main__':
  main()

